//
//  MineProfileTableView.swift
//  MT
//
//  Created by M on 2019/12/29.
//  Copyright © 2019 张强. All rights reserved.
//

import UIKit
import MTCategory

@objc
protocol MineProfileTableViewDelegate: NSObjectProtocol {
    /// 弹出相册
    @objc optional func mineProfileTableViewShouldPresentPhotoLibrary(_ tableView: MineProfileTableView, maxSelectCount: Int, type: MineGalleryCollectionViewCell.Status, withIndexPath indexPath: IndexPath)
    
    @objc optional func mineprofileTableViewShouldPushToTagController(_ tableView: MineProfileTableView, withType type: MTTagViewController.TagType)
}

class MineProfileTableView: UITableView {
    
    /// 交互
    weak var interactionDelegate: MineProfileTableViewDelegate?

    /// sectionHeader标题
    private var sectionHeaderStr: [String] = ["基本信息","详细信息","魅力信息"]

    
    /// 列表控制数组
    private var infoTypes: [[UserProfileInfos]] = [
        [.portrait,.nickname, .birthday, .signature],
                                                   [.body_height, .body_weight, .occupation_position, .degree],
                                                   [.tags, .hobbies]]
    
    /// 图册
    var imageAsset: MTAsset? {
        didSet {
            reloadData()
        }
    }
    
    /// 头像
    var headURL: String?
    
    /// 昵称
    var nickname: String?
    /// 生日
    var birthday: String?
    /// 城市
    var location: String?
    /// 个性签名
    var signature: String?
    /// 身高
    var body_height: Int?
    /// 体重
    var body_weight: Int?
    /// 星座
    var constellation: String?
    /// 行业
    var occupation: String?
    /// 职位
    var occupation_position: String?
    /// 学校
    var school: String?
    /// 学位
    var degree: String?
    /// 我的标签
    var tags: [MTTagModel] = [] {
        didSet {
            tagsHeight = MineTagsTableViewCell.height(for: tags) + 80
            reloadData()
        }
    }
    /// 我的兴趣
    var hobbies: [MTTagModel] = [] {
        didSet {
            hobbiesHeight = MineTagsTableViewCell.height(for: hobbies) + 80
            reloadData()
        }
    }
    
    private var tagsHeight: CGFloat = 50
    private var hobbiesHeight: CGFloat = 50
    
    init(frame: CGRect) {
        super.init(frame: frame, style: .grouped)
        setup()
        contentInset = UIEdgeInsets(top: 0, left: 0, bottom: ScreenBottomExtraOffset, right: 0)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

// MARK: ------------------------------------ 初始化 ----------------------------------------
extension MineProfileTableView {
    
    private func setup() {
        backgroundColor = UIColor(hex:0xf6f6f6)
        delegate = self
        dataSource = self
        separatorStyle = .none
        keyboardDismissMode = .onDrag
        showsVerticalScrollIndicator = false
        contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        
        for types in infoTypes {
            for type in types {
                register(type.cellClass, forCellReuseIdentifier: String(describing: type.cellClass))
            }
        }
    }
    
}

// MARK: ------------------------------------ 刷新界面 ----------------------------------------
extension MineProfileTableView {
    
//    public func refreshGalleryCollectionView(withIdx idx: Int) {
//        for cell in visibleCells {
//            if let c = cell as? MineGalleryTableViewCell {
//                c.collectionView.reloadItems(at: [IndexPath(item: idx, section: 0)])
//                return
//            }
//        }
//    }
    
}

// MARK: ------------------------------------ 所有代理 ----------------------------------------
// MARK: ------------------------------------ UITableViewDelegate ----------------------------------------
extension MineProfileTableView: UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        deselectRow(at: indexPath, animated: false)
        let type = infoTypes[indexPath.section][indexPath.row]
        switch type {
        case .tags, .hobbies:
            if let delegate = interactionDelegate {
                delegate.mineprofileTableViewShouldPushToTagController?(self, withType: type == .tags ? .personality : .hobby)
            }
            break
        default:
            break
        }
    }
    
}

// MARK: ------------------------------------ UITableViewDataSource ----------------------------------------
extension MineProfileTableView: UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return infoTypes.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return infoTypes[section].count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        switch infoTypes[indexPath.section][indexPath.row] {
        case .tags:
            return tagsHeight
        case .hobbies:
            return hobbiesHeight
        default:
            break
        }
        return infoTypes[indexPath.section][indexPath.row].cellHeight
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let type = infoTypes[indexPath.section][indexPath.row]
        let c = tableView.dequeueReusableCell(withIdentifier: String(describing: type.cellClass), for: indexPath)

        switch type {

        case .portrait:
            guard let cell = c as? MTInfoVerificationPortraitCell else {
                break
            }
//            cell.delegate = self
//            cell.models = self.imgList
            cell.type = type
            cell.screenMode = 1
            cell.loadURL = headURL
            cell.asset = imageAsset
            return cell
            
        case .nickname, .signature, .occupation, .occupation_position, .school:
            guard let cell = c as? MTInfoVerificationInputCell else {
                break
            }
            cell.delegate = self
            cell.screenMode = 1
            cell.textFieldTextAlignment = .right
            cell.type = type
            if type == .nickname {
                cell.content = nickname
            } else if type == .signature {
                cell.content = signature
            } else if type == .occupation {
                cell.content = occupation
            } else if type == .occupation_position {
                cell.content = occupation_position
            } else if type == .school {
                cell.content = school
            }
            return cell
            
        case .birthday, .location, .body_height, .body_weight, .constellation , .degree:
            guard let cell = c as? MTInfoVerificationPickerCell else {
                break
            }
            cell.delegate = self
            cell.screenMode = 1
            cell.textFieldTextAlignment = .right
            cell.type = type
            if type == .birthday {
                cell.content = birthday
            } else if type == .location {
                cell.content = location
            } else if type == .body_height {
                cell.content = body_height != nil ? "\(body_height!)cm" : ""
            } else if type == .body_weight {
                cell.content = body_weight != nil ? "\(body_weight!)kg" : ""
            } else if type == .constellation {
                cell.content = constellation
            }  else if type == .degree {
                cell.content = degree
            }
            return cell
            
        case .tags, .hobbies:
            guard let cell = c as? MineTagsTableViewCell else {
                break
            }
            cell.type = type
//            cell.screenMode = 1
            if type == .tags {
                cell.models = tags
            } else if type == .hobbies {
                cell.models = hobbies
            }
            cell.textFieldTextAlignment = .right
            return cell
            
        default: break
        }
        
        return c
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 30
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return CGFloat.leastNonzeroMagnitude
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: 30))
        view.backgroundColor = UIColor(hex:0xf6f6f6)
        let label = UILabel(frame: CGRect(x: 10, y: 0, width: ScreenWidth, height: 30))
        label.text = sectionHeaderStr[section]
        label.textColor = UIColor(hex:0x9b9b9b)
        label.font = PingFangSCMediumFont(14)
        view.addSubview(label)
        return view
//        return nil
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
    
}

// MARK: ------------------------------------ MineGalleryTableViewCellDelegate ----------------------------------------
extension MineProfileTableView: MineGalleryTableViewCellDelegate {
    
//    func galleryTableViewCell(_ cell: MineGalleryTableViewCell, didSelectGalleryCellWithType type: MineGalleryCollectionViewCell.Status, withIndexPath indexPath: IndexPath) {
//        if let delegate = interactionDelegate {
//            delegate.mineProfileTableViewShouldPresentPhotoLibrary?(self, maxSelectCount: 9 - (imgList?.count ?? 0), type: type, withIndexPath: indexPath)
//        }
//    }
    
}

// MARK: ------------------ input delegate ----------------------
extension MineProfileTableView: MTInfoVerificationInputCellDelegate {
    
    func inputCell(_ cell: BaseMTInfoVerificationCell, infoType: UserProfileInfos, didInputText text: String?) {
        switch infoType {
        case .nickname:
            self.nickname = text
            break
        case .birthday:
            self.birthday = text
            break
        case .location:
            self.location = text
            break
        case .signature:
            self.signature = text
            break
        case .body_height:
            if let text = text {
                self.body_height = Int(text.replacingOccurrences(of: "cm", with: ""))
            }
            break
        case .body_weight:
            if let text = text {
                self.body_weight = Int(text.replacingOccurrences(of: "kg", with: ""))
            }
            break
        case .constellation:
            self.constellation = text
            break
        case .occupation:
            self.occupation = text
            break
        case .occupation_position:
            self.occupation_position = text
            break
        case .school:
            self.school = text
            break
        case .degree:
            self.degree = text
            break
        default:
            break
        }
    }
    
}
